package org.windblog.core.servlet.page;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.windblog.core.entity.Page;
import org.windblog.core.PageService;

@SuppressWarnings("serial")
public class SetPageServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String title = req.getParameter("title").trim();
		String content = req.getParameter("content");
		String order = req.getParameter("order");
		int priority = 0;
		if (order != null)
			priority = Integer.parseInt(order);
		String parent = req.getParameter("parent");
		String pagekey = req.getParameter("page");

		Page page = PageService.getPage(pagekey);
		if (page != null) {
			page.setTitle(title);
			page.setPriority(priority);
			page.setContent(content);
			
			Page parentPage = PageService.getParentPage(page);
			if (parent == null || parent.equals("")) {
				Page root = PageService.getRoot();
				
				if(parentPage!=root)
				{
					parentPage.removeChild(page);
					PageService.setPage(parentPage);
					root.addChild(page);
				}
			} else {
				Page pPage = PageService.getPage(parent);
				if (pPage == null)
					resp.sendRedirect("/admin/editPages.jsp?message=5");
				if(parentPage!=pPage)
				{
					parentPage.removeChild(page);
					PageService.setPage(parentPage);
					pPage.addChild(page);
				}
			}
			resp.sendRedirect("/admin/editPages.jsp?message=6");
		}

	}

}
